import os
import sys
from datetime import datetime

from PyQt6.QtCore import Qt
from PyQt6.QtWidgets import QApplication, QWidget, QVBoxLayout, QPushButton, QLabel, QFileDialog, QComboBox, \
    QMessageBox, QHBoxLayout, QProgressDialog, QLineEdit

from addFrame import add_frame_v2, add_watch_frame
from get_resource import resource_path
from logger import Logger
from AddFrameApi import add_frame_to_video, add_watch_frame_to_video
from constans import *
from PIL import Image

# 配置日志logging
now = datetime.now()
logging = Logger(f'log')


class ImageConverterApp(QWidget):
    """主UI界面"""

    def __init__(self):
        super().__init__()
        self.single_image_btn = None  # 单张图片转换按钮变量初始化
        self.batch_image_btn = None  # 批量转换按钮变量初始化
        self.device_type_label = QLabel('选择设备类型：', self)  # 设备类型选择标签
        self.device_combo = QComboBox(self)  # 设备类型选择下拉框
        self.device_combo.currentIndexChanged.connect(self.change_device)  # 设备类型修改回调
        self.model_label = QLabel('选择顶部状态栏样式：', self)  # 顶部状态栏样式标签
        self.mode_combo = QComboBox(self)  # 顶部状态栏选择下拉框
        self.set_dpi = QLabel('分辨率设置：')  # 导出图片分辨率设置
        self.image_height = QLabel('高:')  # 分辨率高设置
        self.image_width = QLabel('宽:')  # 分辨率高设置
        self.height_line = QLineEdit()  # 高输入框
        self.width_line = QLineEdit()  # 宽输入框
        self.progress_dialog = None  # 视频转换进度条变量初始化

        self.init_ui()
        self.script_path = os.getcwd()

    def init_ui(self):
        logging.info('初始化UI界面')
        self.setWindowTitle('自动加机框工具')
        self.setGeometry(300, 300, 300, 150)

        # 主布局
        layout = QVBoxLayout()

        # 选择设备类型
        first_hbox1 = QHBoxLayout()
        first_hbox1.addWidget(self.device_type_label)
        self.device_combo.addItem('phone')
        self.device_combo.addItem('fold')
        self.device_combo.addItem('table')
        self.device_combo.addItem('pc')
        self.device_combo.addItem('tv')
        self.device_combo.addItem('watch')
        first_hbox1.addWidget(self.device_combo)
        layout.addLayout(first_hbox1)

        # 转换模式选择
        first_hbox2 = QHBoxLayout()
        first_hbox2.addWidget(self.model_label)
        self.mode_combo.addItem('default')
        self.mode_combo.addItem('white')
        self.mode_combo.addItem('grey')
        self.mode_combo.addItem('black')
        self.mode_combo.addItem('immersive')
        first_hbox2.addWidget(self.mode_combo)
        layout.addLayout(first_hbox2)

        # 分辨率设置
        hbox3 = QHBoxLayout()
        hbox3.addWidget(self.set_dpi)
        hbox3.addWidget(self.image_height)
        self.height_line.textChanged.connect(self.calculate_dpi)
        hbox3.addWidget(self.height_line)
        hbox3.addWidget(self.image_width)
        self.width_line.textChanged.connect(self.calculate_dpi)
        hbox3.addWidget(self.width_line)
        layout.addLayout(hbox3)

        # 单张图片转换
        self.single_image_btn = QPushButton('单张图片转换', self)
        self.single_image_btn.clicked.connect(self.convert_single_image)
        layout.addWidget(self.single_image_btn)

        # 批量图片转换
        self.batch_image_btn = QPushButton('批量图片转换', self)
        self.batch_image_btn.clicked.connect(self.convert_batch_images)
        layout.addWidget(self.batch_image_btn)

        # 设置布局
        self.setLayout(layout)

    def change_device(self):
        """修改默认分辨率显示"""
        current_device_type = self.device_combo.currentText()
        frame_path = resource_path(f'resource/{current_device_type}/机框.png')
        frame = Image.open(frame_path).convert('RGBA')
        self.height_line.setText(str(frame.height))
        self.width_line.setText(str(frame.width))

    def calculate_dpi(self):
        # 获取发射信号的对象
        sender = self.sender()

        current_device_type = self.device_combo.currentText()
        frame_path = resource_path(f'resource/{current_device_type}/机框.png')
        frame = Image.open(frame_path).convert('RGBA')
        if sender == self.height_line and self.height_line.text() != '':
            # 临时阻断width_line的信号防止循环
            self.width_line.blockSignals(True)
            current_wight = int(int(self.height_line.text()) * (frame.width / frame.height))
            self.width_line.setText(str(current_wight))
            self.width_line.blockSignals(False)  # 恢复信号
        elif sender == self.width_line and self.width_line.text() != '':
            # 临时阻断height_line的信号防止循环
            self.height_line.blockSignals(True)
            current_height = int(int(self.width_line.text()) * (frame.height / frame.width))
            self.height_line.setText(str(current_height))
            self.height_line.blockSignals(False)  # 恢复信号

    def convert_single_image(self):
        """单张图片转换"""
        # 打开文件对话框选择单张图片
        file_name, _ = QFileDialog.getOpenFileName(self, '选择图片', '', '*.png *.jpg *.bmp *mp4 *jpeg')
        if file_name:
            logging.info(f'图片选择成功：{file_name}')
            self.convert_image(file_name, file_name='', single=True)
            logging.info(f'图片转换成功：{file_name}')

    def convert_batch_images(self):
        """批量转换"""
        # 打开文件堆化框选择目录
        directory = QFileDialog.getExistingDirectory(self, '选择目录')
        if directory:
            logging.info(f'目录选择成功：{directory}')
            # 遍历目录中的图片文件
            for file_name in os.listdir(directory):
                if file_name.lower().endswith(('.png', '.jpg', '.bmp', '.mp4', '.jpeg')):
                    self.convert_image(os.path.join(directory, file_name), file_name)
            QMessageBox.information(self, '转换完成', f'图片已批量转换成功')
            logging.info(f'图片已批量转换成功')

    def convert_image(self, file_path, file_name, single=None):
        """图片加机框"""
        # 获取选择的转换模式和设备类型
        mode = self.mode_combo.currentText()
        current_device_type = self.device_combo.currentText()

        # 根据选择的模式进行转换
        if mode == 'default':
            # 不设置状态栏
            top_img = None
        else:
            # 设置状态栏颜色
            top_img = resource_path(f'resource/{current_device_type}/top_{mode}.png')
            # 如果资源库中不存在，则采用默认
            if not os.path.exists(top_img):
                logging.info(f'{current_device_type}产品无该资源，采用默认状态栏')
                top_img = None

        logging.info(f'当前选择顶部状态栏样式为：{top_img}')
        file_path = file_path.replace('\\', '/')
        converted_filename = file_path.replace('.', '_converted.')

        if not os.path.exists('converted_image'):
            os.makedirs('converted_image')
        if not file_path.endswith('.mp4'):
            converted_filename = ''.join(converted_filename.split('.')[0: -1]) + '.png'
            new_file_path = os.path.join(os.path.join(self.script_path, 'converted_image'),
                                         converted_filename.split('/')[-1])
            frame_path = resource_path(f'resource/{current_device_type}/机框.png')
            if current_device_type == 'phone':
                Phone.DPI = (int(self.width_line.text()), int(self.height_line.text()))
                add_frame_v2(file_path, frame_path, top_img, new_file_path, Phone)
            elif current_device_type == 'fold':
                Fold.DPI = (int(self.width_line.text()), int(self.height_line.text()))
                add_frame_v2(file_path, frame_path, top_img, new_file_path, Fold)
            elif current_device_type == 'table':
                Table.DPI = (int(self.width_line.text()), int(self.height_line.text()))
                add_frame_v2(file_path, frame_path, top_img, new_file_path, Table)
            elif current_device_type == 'pc':
                PC.DPI = (int(self.width_line.text()), int(self.height_line.text()))
                add_frame_v2(file_path, frame_path, top_img, new_file_path, PC)
            elif current_device_type == 'tv':
                TV.DPI = (int(self.width_line.text()), int(self.height_line.text()))
                add_frame_v2(file_path, frame_path, top_img, new_file_path, PC)
            elif current_device_type == 'watch':
                add_watch_frame(file_path, frame_path, new_file_path)
        else:
            # 创建一个进度对话框
            self.progress_dialog = QProgressDialog(f'视频转化中...', '取消', 0, 100, self)
            self.progress_dialog.setWindowTitle(f'{file_name} Transforming')
            self.progress_dialog.setWindowModality(Qt.WindowModality.WindowModal)
            self.progress_dialog.setCancelButtonText(None)
            self.progress_dialog.setAutoReset(True)
            self.progress_dialog.setAutoClose(True)

            converted_filename = ''.join(converted_filename.split('.')[0: -1]) + '.webp'
            new_file_path = os.path.join(os.path.join(self.script_path, 'converted_image'),
                                         converted_filename.split('/')[-1])
            frame_path = resource_path(f'resource/{current_device_type}/机框.png')
            if current_device_type == 'phone':
                Phone.DPI = (int(self.width_line.text()), int(self.height_line.text()))
                add_frame_to_video(file_path, frame_path, top_img, new_file_path, Phone,
                                   progress_dialog=self.progress_dialog)
            elif current_device_type == 'fold':
                add_frame_to_video(file_path, frame_path, top_img, new_file_path, Fold,
                                   progress_dialog=self.progress_dialog)
            elif current_device_type == 'table':
                Table.DPI = (int(self.width_line.text()), int(self.height_line.text()))
                add_frame_to_video(file_path, frame_path, top_img, new_file_path, Table,
                                   progress_dialog=self.progress_dialog)
            elif current_device_type == 'pc':
                PC.DPI = (int(self.width_line.text()), int(self.height_line.text()))
                add_frame_to_video(file_path, frame_path, top_img, new_file_path, PC,
                                   progress_dialog=self.progress_dialog)
            elif current_device_type == 'tv':
                TV.DPI = (int(self.width_line.text()), int(self.height_line.text()))
                add_frame_to_video(file_path, frame_path, top_img, new_file_path, TV,
                                   progress_dialog=self.progress_dialog)
            elif current_device_type == 'watch':
                add_watch_frame_to_video(file_path, frame_path, new_file_path, progress_dialog=self.progress_dialog)

        if single:
            QMessageBox.information(self, '转换完成', f'图片已转换并保存为 {new_file_path}')
            logging.info(f'图片已转换并保存为 {new_file_path}')


if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = ImageConverterApp()
    ex.show()
    sys.exit(app.exec())
